package com.lby.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.lby.Application;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * sa-token使用参考
 * https://sa-token.cc/doc.html#/use/login-auth
 * https://sa-token.cc/doc.html#/use/jur-auth
 */

@RestController
@RequestMapping("/user/")
public class UserController {

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    // 测试登录，浏览器访问： http://localhost:20891/user/doLogin?username=zhang&password=123456
    @RequestMapping("doLogin")
    public SaResult doLogin(String username, String password) {
        // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对
        if("zhang".equals(username) && "123456".equals(password)) {
            StpUtil.login(10001);
            return SaResult.ok("登录成功");
        } else if ("zhang2".equals(username)){
            StpUtil.login(10002);
            return SaResult.ok("登录成功");
        }
        return SaResult.error("login error");
    }


    // 查询登录状态，浏览器访问： http://localhost:20891/user/isLogin
    @RequestMapping("isLogin")
    public SaResult isLogin() {
        System.out.println("islonin:" + StpUtil.isLogin() );
        return  SaResult.data(StpUtil.getTokenInfo());
    }

    @RequestMapping("checkLonin")
    public SaResult checkLonin() {
        StpUtil.checkLogin();
        Long id = StpUtil.getLoginIdAsLong();
        //权限检验
        StpUtil.checkPermission("user.add");
        logger.info("permission list: {}", StpUtil.getPermissionList(id));
        logger.info("user.add : {}", StpUtil.hasPermission("user.add"));

        //角色检验
        StpUtil.checkRole("admin");
        logger.info("role list: {}", StpUtil.getRoleList(id));

        return  SaResult.data("登录成功才看到这一信息");
    }

    @RequestMapping("longout")
    public SaResult longout() {
        StpUtil.logout(10001);
        return  SaResult.data("10001退出登录");
    }

}
